package com.itheima.controller;

import com.itheima.entity.Dept;
import com.itheima.entity.Result;
import com.itheima.service.DeptService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//请求处理类
//@Controller
@Slf4j  //会自动生成log对象用于打印日志
@RequestMapping("/depts") //可以添加路径前缀
@RestController//@controller+@ResponseBody将返回的对象和集合自动转换成json数据
public class   DeptController {

//@Autowired//通过ioc容器自动获取对象
@Resource(name = "deptServiceImpl")
private DeptService deptService;
    @GetMapping// @RequestMapping(value = "/depts",method = RequestMethod.GET)等价于限制请求方式为get
    public Result list()
    {

        //1.调用Service查询所有部门信息
        List<Dept> depts = deptService.list();
        for (Dept dept : depts) {
            log.info("dept: {}", dept);
        }

        //2.响应数据
        return Result.success(depts);
    }
    //原始方式获取数据
//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest  request)
//    {
//        String id = request.getParameter("id");
//        int idInt= Integer.parseInt(id);
//
//        return Result.success();
//
//    }
    @DeleteMapping
    public Result delete(Integer  id)
    {
        log.info("deptId={}",id);

        //调用service删除方法
        deptService.delete(id);

        return Result.success();

    }

    @PostMapping
    public Result save(@RequestBody Dept dept)
    {
        log.info("dept={}",dept);
      //  try {
            deptService.save(dept);
     //   } catch (Exception e) {
            //throw new RuntimeException(e);
        //    return Result.error("该部门已存在");
    //    }


        return Result.success();

    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id)
    {
        log.info("deptId={}",id);
//        调用service方法
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    //修改部门
    @PutMapping
    public Result update(@RequestBody Dept dept)
    {
        log.info("dept={}",dept);
        deptService.update(dept);
        return Result.success();
    }




}
